<template>
  <div>
    <h3>实时产量(每5分钟更新)</h3>
    <el-col :span="24">
      <div class="block">
        <el-date-picker
  v-model="value2"
  type="datetimerange"
  :shortcuts="shortcuts"
  range-separator="To"
  start-placeholder="起始日期"
  end-placeholder="结束日期"
  :default-time="['00:00:00', '00:00:00']" 
  :picker-options="{ 
    start: {  
      disabledMinutes: () => { return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]; }, 
      disabledSeconds: () => { return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]; }, 
    },
  }"
/>
        <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </el-col>
    <div ref="chart" style="height: 500px; width: 1300px"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import axios from "axios";

const value2 = ref([]);
const shortcuts = [
  {
    text: "当天",
    value: () => {
      const now = new Date();
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      return [start, now];
    },
  },
];
const value3 = ref('get_LoopA_hourly_production_data/');
  const options = [
    {value: "get_LoopA_hourly_production_data/",label: "装配A"},
    {value: "get_LoopB_hourly_production_data/",label: "装配B"},
    {value: "get_LoopC_hourly_production_data/",label: "装配C"},
    {value: "get_BK_M1_hourly_production_data/",label: "缸体M1"},
    {value: "get_Bk_M2_hourly_production_data/",label: "缸体M2"},
    {value: "get_HD_M1_hourly_production_data/",label: "缸盖M1"},
    {value: "get_HD_M2_hourly_production_data/",label: "缸盖M2"},
    {value: "get_Ck_M1_hourly_production_data/",label: "曲轴"},

  ]; 
const chart = ref(null);
let chartInstance;

function initChart(data) {
  chartInstance = echarts.init(chart.value);

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const stationName = params[0].name;
        let result = `<div>${stationName}</div>`;
        params.forEach(param => {
          result += `<div>${param.seriesName}: ${param.value}</div>`;
        });
        return result;
      },
    },
    legend: {
      data: [], 
      orient: 'vertical',
      right: '10',
      top: 'center'
    },
    title: {
      text: '产量统计',
      left: 'center',
      textStyle: {
        color: 'black',
      },
      subtext: '单位：台',
      subtextStyle: {
        fontWeight: 'bold',
      },
    },
    xAxis: {
      name: '工位',
      type: 'category',
      axisLabel: {
        rotate: 45 
      },
      data: Object.keys(data[0]).filter(k => k.startsWith('OP') || k.startsWith('M1_op')|| k.startsWith('M2_op')|| k.startsWith('HD_M1_op')|| k.startsWith('HD_M2_op')|| k.startsWith('CK_M1_op')),
    },
    yAxis: {
      type: 'value',
    },
    series: [],
    dataZoom: [
      {
        type: 'slider',  
        show: true,      
        start: 0,
        end: 100,
        top: '97%'       
      },
      {
        type: 'inside',
        start: 90,
        end: 100,
      },
    ],
  };

  data.forEach((item, index) => {
    const values = Object.values(item).filter(v => typeof v === 'number');
    if (values.some(value => value > 0)) { // 如果该系列中有任何值大于0
      option.series.push({
        name: item.timeRange,
        type: 'bar',
        stack: 'total',
        data: values,
      });
      option.legend.data.push(item.timeRange); // 只有当数据不全为0时才添加到图例中
    }
  });

  chartInstance.setOption(option);
}
  
onMounted(() => {
  value2.value = [new Date(new Date().setHours(8, 0, 0, 0)), new Date()];
  fetchData();
});

function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

watch([value2, value3],([newValue2, newValue3]) => {
  const start_time = formatDate(newValue2[0]);
  const end_time = formatDate(newValue2[1]);
  fetchData(start_time, end_time,newValue3);
});

async function fetchData(startTime, endTime,assembly) {
  const url = `http://10.64.35.32:8000/man_ana_sql_server/${assembly}?start_time=${startTime}&end_time=${endTime}&page_size=10001`;
  try {
    const response = await axios.get(url);
    console.log(url)
    const data = response.data;
    const processedData = processHourlyProductionData(data);
    console.log(processedData)
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null; // 清除引用以便于垃圾回收
    }
    initChart(processedData);
  } catch (error) {
    console.error(error);
  }
}

function processHourlyProductionData(data) {
  const hourlyData = [];
  let prevHourData = {};
  const excludedStations = ['CK_M1_op008','CK_M1_op010g','CK_M1_op015a','CK_M1_op015b','CK_M1_op020g','CK_M1_op048','CK_M1_op075','M1_op075','M1_op125','M1_op195','M2_op075','M2_op125','HD_M1_op065','HD_M1_op145','HD_M1_op175','HD_M1_op178','HD_M2_op065','HD_M2_op145','HD_M2_op175','HD_M2_op178','M2_op195','M1_oplg02','OP1006', 'OP1008','OP1035','OP1040','OP2040','OP2100','OP2115','OP2120','OP2135','OP213a','OP2145','OP2146','OP2150','OP2155','OP2196','OP2225','OP2236','OP2260','OP2270','OP2325','OP2330','OP2355','OP2356','OP2380','OP2420','OP2430','OP2440','OP2450','OP2476','OP2505','OP2515','OP5010','OP5020','OP6010','OP7010','OP7020','OP7030','OP303a','OP305b','OP3062','OP3063','OP3105','OP2006','OP2055','OP1070','OP1075','OP1095','OP1096','OP1115','OP1126','OP1150','OP1165','OP1195','OP1196','OP121a','OP121b','OP1235','OP1245','OP4010','OP1130','OP1290','OP1265','OP1266','OP1315','OP1366','OP1368','OP143b','OP1405','OP1416','OP1420','OP1445','OP4050','OP4020','OP1053','OP1058'];
  const currentTime = new Date(); // 获取当前时间
  const currentHour = currentTime.getHours();
  let hourProcessed = false;

  data.forEach(item => {
    const timestamp = item.timestamp;
    const hour = new Date(timestamp).getHours();

    if (hour % 1 === 0 && [0, 1, 2, 3, 4].includes(new Date(timestamp).getMinutes())) {
    if (!hourProcessed) {
      if (!prevHourData.timestamp) {
        prevHourData = item;
        hourlyData.push(item);
      } else {
        const hourlyProduction = calculateHourlyProduction(item, prevHourData);
        hourlyData.push(hourlyProduction);
      }
      prevHourData = item;
      hourProcessed = true; 
    }
  } else {
    hourProcessed = false; 
  }
  });

  if (new Date(data[data.length - 1].timestamp).getMinutes() !== 0) {
    const latestHourlyProduction = calculateHourlyProduction(data[data.length - 1], prevHourData);
    hourlyData.push(latestHourlyProduction);
  }
  hourlyData.shift();
  hourlyData.forEach((item, index) => {
    excludedStations.forEach(excludedStation => {
      delete item[excludedStation]; // 删除被屏蔽的工位数据
    });

    const startHour = new Date(item.timestamp).getHours()-1;
    const endHour = startHour + 1;

    if (index === hourlyData.length - 1 && currentTime.getMinutes() !== 0) {
      item.timeRange = `${endHour}:00-${endHour + 1}:00`; 
    } else {
      item.timeRange = `${startHour}:00-${endHour}:00`;
    }
  });

  return hourlyData;
}

function calculateHourlyProduction(currentData, prevData) {
  const result = { ...currentData };
  const keys = Object.keys(currentData);
  keys.forEach(key => {
    if (key.startsWith('OP') || key.startsWith('M1_op')|| key.startsWith('M2_op')|| key.startsWith('HD_M1_op')|| key.startsWith('HD_M2_op')|| key.startsWith('CK_M1_op')) {
      result[key] = Math.max(currentData[key] - (prevData[key] || 0), 0);
    }
  });
  return result;
}
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
}
</style>